﻿using ERP.ERPSystem.OrderManagement;
using ERP.ERPSystem.OrderManagement.Dto;
using ERP.Team.OrderManagement;
using ERP.Web.Models.OrderManagement;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using Volo.Abp.AspNetCore.Mvc;

namespace ERP.Web.Controllers.OrderManagement
{
    public class SalesOrderController : AbpController
    {
        private readonly ISalesOrderServices _salesOrderServices;
        private readonly ILogger<SalesOrderController> _logger;

        public SalesOrderController(ISalesOrderServices salesOrderServices, ILogger<SalesOrderController> logger)
        {
            _salesOrderServices = salesOrderServices;
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Add()
        {
            return View();
        }

        public IActionResult Edit(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        [HttpGet]
        public IActionResult GenerateOrderCode()
        {
            var orderCode = _salesOrderServices.GenerateOrderCode();
            return Json(new { code = 0, data = orderCode });
        }

        [HttpGet]
        public async Task<IActionResult> GetCustomerList()
        {
            var list = await _salesOrderServices.GetCustomerListAsync();
            return Json(new { code = 0, msg = "", count = list.Count, data = list });
        }

        [HttpPost]
        public async Task<IActionResult> GetList([FromBody] ERPSystem.OrderManagement.Dto.SalesOrderQueryDto query)
        {
            try
            {
                query = query ?? new ERPSystem.OrderManagement.Dto.SalesOrderQueryDto();
                var list = await _salesOrderServices.GetListAsync(query);
                return Json(new { code = 0, msg = "获取成功", count = list.Count, data = list });
            }
            catch (Exception ex)
            {
                _logger.LogError($"获取销售订单列表失败：{ex}");
                return Json(new { code = 1, msg = "获取失败：" + ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] SalesOrderViewModel model)
        {
            if (model == null)
            {
                return new JsonResult(new { code = 1, msg = "提交的数据不能为空" });
            }

            try
            {
                var dto = new SalesOrderDto
                {
                    OrderCode = model.OrderCode,
                    OrderName = model.OrderName,
                    CustomerCode = model.CustomerCode,
                    CustomerName = model.CustomerName,
                    OrderDate = model.OrderDate,
                    DeliveryDate = model.DeliveryDate,
                    SettlementMethod = model.SettlementMethod,
                    OrderCategory = model.OrderCategory,
                    Salesperson = model.Salesperson,
                    QualityRequirement = model.QualityRequirement,
                    Remark = model.Remark,
                    Products = model.Products?.Select(p => new SalesOrderProductDetailDto
                    {
                        ProductCode = p.ProductCode,
                        ProductName = p.ProductName,
                        Material = p.Material,
                        Color = p.Color,
                        OrderQuantity = p.OrderQuantity,
                        UnitQuantity = p.UnitQuantity,
                        Amount = p.Amount,
                        OrderGoodsTime = p.OrderGoodsTime,
                        DeliveryTime = p.DeliveryTime
                    }).ToList()
                };

                var result = await _salesOrderServices.CreateAsync(dto);
                return new JsonResult(new { code = 0, msg = "添加成功", orderCode = result.OrderCode });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { code = 1, msg = $"添加失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Update([FromBody] ERPSystem.OrderManagement.Dto.SalesOrderDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Json(new { code = 1, msg = "提交的数据不能为空" });
                }

                if (dto.Id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的订单ID" });
                }

                _logger.LogInformation($"Updating order with ID: {dto.Id}");
                _logger.LogInformation($"Update DTO: {System.Text.Json.JsonSerializer.Serialize(dto)}");

                var result = await _salesOrderServices.UpdateAsync(dto);
                return Json(new { code = 0, msg = "修改成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error updating order: {ex}");
                return Json(new { code = 1, msg = $"更新失败：{ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            await _salesOrderServices.DeleteAsync(id);
            return Json(new { code = 0, msg = "删除成功" });
        }

        [HttpGet]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                var model = await _salesOrderServices.GetByIdAsync(id);
                if (model == null)
                {
                    return Json(new { code = 1, msg = "订单不存在" });
                }

                // 格式化日期
                if (model.OrderDate.HasValue)
                {
                    model.OrderDate = DateTime.SpecifyKind(model.OrderDate.Value, DateTimeKind.Local);
                }
                if (model.DeliveryDate.HasValue)
                {
                    model.DeliveryDate = DateTime.SpecifyKind(model.DeliveryDate.Value, DateTimeKind.Local);
                }

                return Json(new { code = 0, msg = "", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error getting order: {ex}");
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetProductList(string productCode = "", string productName = "")
        {
            try
            {
                var products = await _salesOrderServices.GetProductListAsync();
                
                // 应用搜索过滤
                if (!string.IsNullOrEmpty(productCode))
                {
                    products = products.Where(p => p.ProductCode.Contains(productCode, StringComparison.OrdinalIgnoreCase)).ToList();
                }
                if (!string.IsNullOrEmpty(productName))
                {
                    products = products.Where(p => p.ProductName.Contains(productName, StringComparison.OrdinalIgnoreCase)).ToList();
                }

                return new JsonResult(new { 
                    code = 0, 
                    msg = "获取成功", 
                    count = products.Count,
                    data = products 
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { code = 1, msg = $"获取失败: {ex.Message}" });
            }
        }

        [HttpGet]
        public IActionResult ProductList()
        {
            return View();
        }
    }
}
